<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <div class="login-title">系统登录</div>

      <el-form
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          class="login-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              :loading="loginLoading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
// 导入登录接口
import { login } from '@/api/auth'

const router = useRouter()
const loginFormRef = ref(null)
const loginLoading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: 'admin', // 默认用户名
  password: 'admin123' // 默认密码，实际项目中应清空
})

// 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

// 登录处理函数
const handleLogin = async () => {
  // 表单验证
  const valid = await loginFormRef.value.validate()
  if (!valid) return

  try {
    loginLoading.value = true
    // 调用登录接口
    const response = await login(loginForm)

    // 假设接口返回格式：{ code: 200, data: { token: 'xxx' }, msg: '登录成功' }
    if (response.code === 200) {
      // 存储token
      localStorage.setItem('token', response.data.token)
      ElMessage.success('登录成功')

      // 登录成功后跳转到首页（与动态路由平级）
      router.push('/dashboard')
    } else {
      ElMessage.error(response.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请重试')
  } finally {
    loginLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  border-radius: 8px;
}

.login-title {
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 30px;
  color: #1f2329;
}

.login-form {
  padding: 0 20px;
}

.login-btn {
  width: 100%;
}
</style>
